package org.zzk.util;

import io.netty.channel.Channel;
import org.zzk.dao.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class MatchPool {
    private static final MatchPool INSTANCE = new MatchPool();
    private final ConcurrentHashMap<String, Player> waitingPlayers = new ConcurrentHashMap<>();

    public static MatchPool getInstance() {
        return INSTANCE;
    }

    public synchronized MatchResult addPlayer(Player player, int gameTimeLimitMs) {
        waitingPlayers.put(player.getId(), player);

        // 简单匹配算法：相同时间要求的玩家匹配
        Optional<Player> opponent = waitingPlayers.values().stream()
                .filter(p -> !p.getId().equals(player.getId()))
                .filter(p -> Math.abs(p.getGameTimeLimitMs() - gameTimeLimitMs) == 0)
                .findFirst();

        if (opponent.isPresent()) {
            waitingPlayers.remove(player.getId());
            waitingPlayers.remove(opponent.get().getId());

            String roomId = "room_" + System.currentTimeMillis();
            opponent.get().setRed(!player.isRed());
            Room room = new Room(roomId, Arrays.asList(player, opponent.get()), new ChessGame());
            RoomManager.getInstance().addRoom(room);

            room.initCurrentPlayer();

            return MatchResult.success(roomId, opponent.get());
        }

        return MatchResult.waiting();
    }

    public Player removePlayer(Channel ch) {
        // 先快速检查（非同步）
        for (Player player : waitingPlayers.values()) {
            if (player.getChannel().equals(ch)) {
                // 二次检查（同步块）
                synchronized (this) {
                    Player confirmed = waitingPlayers.get(player.getId());
                    if (confirmed != null && confirmed.getChannel().equals(ch)) {
                        waitingPlayers.remove(player.getId());
                        return player;
                    }
                }
            }
        }
        return null;
    }
}
